<?php
/**
 * Created by PhpStorm.
 * User: prg
 * Date: 2017/2/28
 * Time: 19:29
 */

//管理员修改用户密码功能接口
require_once 'db.php';
require_once 'response.php';

header('content-type:text/html;charset:utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

$username = isset($_POST['username']) ? $_POST['username'] : '';
$newPassword = isset($_POST['newPassword']) ? $_POST['newPassword'] : '';

if(empty($username) || empty($newPassword)) {
    return Response::show(401,'数据不合法');
}

//连接数据库
try {
    $connect = Db::getInstance()->connect();
} catch (Exception $e) {
//    $e->getMessage();
    return Response::show(403,'数据库连接失败',$e->getMessage());
}

$sql = "SELECT user_type FROM user WHERE username=?";
$mysqli_stmt = $connect->prepare($sql);
$mysqli_stmt->bind_param('s',$username);

$data = array(
    'IsUpdate' => false,
);

if($mysqli_stmt->execute()) {
    $mysqli_stmt->bind_result($type);
    if($mysqli_stmt->fetch()) {

        if($type == 0) {
            return Response::show(402,'权限不足,无法修改密码',$data);
        } else {
            //是普通用户就可以修改密码了，先把预处理语句关闭
            $mysqli_stmt->free_result();
            $mysqli_stmt->close();
            //再开一个预处理语句用于修改密码
            $sql = "UPDATE user SET password=? WHERE username='{$username}'";
            $mysqli_stmt = $connect->prepare($sql);
            $mysqli_stmt->bind_param('s',$newPassword);

            if($mysqli_stmt->execute()) {
                if(!$mysqli_stmt->error) {
                    $data['IsUpdate'] = true;
                    return Response::show('200','密码修改成功',$data);
                } else {
                    return Response::show('406','密码修改失败',$data);
                }
            } else {
                return Response::show('405','修改密码不执行',$data);
            }
        }//end of update

    } else {
        return Response::show('400','用户名错误,修改密码无法执行',$data);
    }//end of result
} else {
    return Response::show('404','修改密码失败,服务器没响应',$data);
}//end of select



